<template>
  <div class="common-layout">
    <el-container>
      <el-aside width="200px">
        <el-affix :offset="10">
          <el-radio-group v-model="isCollapse" style="margin-bottom: 20px">
            <el-radio-button :value="false">展开</el-radio-button>
            <el-radio-button :value="true">折叠</el-radio-button>
          </el-radio-group>
          <el-menu default-active="1" class="el-menu-vertical-demo" :collapse="isCollapse" @open="handleOpen"
            @close="handleClose" @select="handleSelect">
            <el-menu-item index="/index">
              <el-icon>
                <House />
              </el-icon>
              <template #title>首页 </template>
            </el-menu-item>
            <el-menu-item index="/booklist">
              <el-icon>
                <Folder />
              </el-icon>
              <template #title>图书列表</template>
            </el-menu-item>
            <el-menu-item index="/booksales">
              <el-icon>
                <Reading />
              </el-icon>
              <template #title>图书售卖</template>
            </el-menu-item>
            <el-menu-item index="/help">
              <el-icon>
                <Warning />
              </el-icon>
              <template #title>帮助</template>
            </el-menu-item>
          </el-menu>
          <!-- 路由出口，用于显示当前路由对应的组件 -->
          <router-view></router-view>
        </el-affix>
      </el-aside>
      <el-container>
        <el-affix :offset="0">
          <el-header style="
              display: flex;
              align-items: center;
              height: 60px;
              border: 1px solid #f5f6fe;
            ">
            <!-- 添加 flex-grow: 1 使该 div 占据剩余空间 -->
            <div style="flex-grow: 1"></div>

            <router-link to="/cart" style="
                display: flex;
                align-items: center;
                justify-content: center;
                height: 50px;
                padding-right: 20px;
                text-decoration: none; /* 去除默认下划线 */
                color: inherit; /* 继承父元素颜色 */
              ">
              <el-badge :value="bookStore.orderedBooksCount" :max="10" class="badge-item">
                <span class="icon-wrapper">
                  <el-icon style="font-size: 25px">
                    <ShoppingCart />
                  </el-icon>
                </span>
              </el-badge>
            </router-link>

            <div style="
                display: flex;
                align-items: center;
                justify-content: center;
                height: 50px;
                padding-right: 20px;
              ">
              <span class="icon-wrapper">
                <el-icon style="font-size: 25px">
                  <Setting />
                </el-icon>
              </span>
            </div>

            <div style="padding-right: 20px">
              <el-popover placement="bottom" trigger="hover">
                <el-menu mode="vertical">
                  <el-menu-item index="1" @click="handleMenuItemClick(1)">个人中心</el-menu-item>
                  <el-menu-item index="2" @click="handleMenuItemClick(2)">关于我们</el-menu-item>
                  <el-menu-item index="3" @click="handleMenuItemClick_exit(3)">退出登录</el-menu-item>
                </el-menu>

                <template #reference>
                  <el-avatar src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png" />
                </template>
              </el-popover>
            </div>
          </el-header>
        </el-affix>
        <el-main>
          <h3 style="text-align: left">我的图书</h3>
          <div class="mt-4" style="width: 50%">
            <el-input v-model="searchText" style="width: 100%" placeholder="请输入搜索内容" class="input-with-select"
              @keyup.enter="handleSearch">
              <template #prepend>
                <el-button :icon="Search" @click="handleSearch" />
              </template>
            </el-input>
          </div>

          <el-row>
            <!-- 遍历书籍列表 -->
            <el-col :xs="8" :sm="6" :lg="4" :xl="1" v-for="(book, index) in filteredBooklist" :key="book.title">
              <!-- 遍历书籍列表 -->
              <div class="booklistdiv">
                <!-- 显示书籍图片 -->
                <img :src="book.img" alt="book cover" class="book-image" />
                <div class="booktitle">
                  <!-- 显示书籍标题 -->
                  <h4>
                    {{ book.title }}
                    <span class="overflow-menu-icon" @click="toggleDetails(index)">
                      <svg class="icon" aria-hidden="true">
                        <use xlink:href="#icon-gengduo-shuxiang"></use>
                      </svg>
                    </span>
                  </h4>

                  <!-- 显示书籍作者 -->
                  <p>作者: {{ book.author }}</p>
                  <!-- 显示书籍价格 -->
                  <p>价格: {{ book.price }}</p>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-main>
        <el-footer style="
            display: flex;
            justify-content: center;
            align-items: center;
            height: 60px;
          ">
          <div>Designed with by XXX</div>
        </el-footer>
      </el-container>
    </el-container>
  </div>
</template>


<script lang="ts" setup>
import { reactive } from "vue";
import { ref, computed } from "vue";
import {
  Reading,
  House,
  Warning,
  Folder,
  Search,
  ArrowRight,
  CaretBottom,
  CaretTop,
  Top,
  Bottom,
  Close,
  Setting,
  ShoppingCart,
} from "@element-plus/icons-vue";
import type { TabsPaneContext } from "element-plus";
import { onMounted } from "vue";
import { useRouter } from "vue-router";
import {
  ElPopover,
  ElAvatar,
  ElMenu,
  ElMenuItem,
  ElMessage,
  ElMessageBox,
} from "element-plus";
// 引入 newBook.js 文件中的书籍数据
import originalBooklist from "../mock/index.ts";
import "../mock/iconfont.js";
import { useLogout } from "../composables/useLogout";
import { useBookStore } from '../stores/bookStore';

const router = useRouter();
const bookStore = useBookStore();

// 将导入的 booklist 转换为响应式数据
const booklist = ref<Book[]>(originalBooklist);

const toggleDetails = (index: number) => {
  booklist.value[index].isDetailsVisible =
    !booklist.value[index].isDetailsVisible;

  const currentBook = booklist.value[index];

  // 将 bookInfo 改为对象格式
  const bookInfo = {
    title: currentBook.title,
    author: currentBook.author,
    price: currentBook.price,
    img: currentBook.img,
    quantity: 1,
  };

  const infoText = `书名: ${bookInfo.title}\n作者: ${bookInfo.author}\n价格: ${bookInfo.price}\n`;

  ElMessageBox.confirm(
    `<div class="message-box-content">是否确认订购以下书籍？<br>${infoText.replace(
      /\n/g,
      "<br>"
    )}</div>`,
    "详情",
    {
      confirmButtonText: "订购",
      cancelButtonText: "取消",
      type: "info",
      center: true,
      dangerouslyUseHTMLString: true,
    }
  )
    .then(() => {
      // 点击订购时将 bookInfo 存入 Pinia
      bookStore.addOrderedBook(bookInfo);
      ElMessage({
        type: "success",
        message: `${bookInfo.title}订购完成`,
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: `${bookInfo.title}订购取消`,
      });
    });
};

onMounted(() => {
  const userData = localStorage.getItem("userData");
  if (!userData) {
    // 如果没有获取到数据，跳转到登录页
    router.push("/login");
  }
});

// 定义书籍对象的类型
interface Book {
  title: string;
  img: string;
  price: number;
  author: string;
  isDetailsVisible: boolean;
};

// 定义 imageItem 类型
interface ImageItem {
  src: string;
  alt: string;
  bgColor: string;
}

const isCollapse = ref(false);

// 创建一个响应式的布尔变量，初始值设为true，表示div初始是可见的
const isDivVisible = ref(true);

const handleOpen = (key: string, keyPath: string[]) => {
  console.log(key, keyPath);
};
const handleClose = (key: string, keyPath: string[]) => {
  console.log(key, keyPath);
};

const handleSelect = (key: string) => {
  // 根据菜单项的 index 值切换页面

  router.push(key);
};

const searchText = ref("");

const handleMenuItemClick = (index: number) => {
  console.log(`你点击了选项 ${index}`);
};

const { isLoading, logout } = useLogout();
const handleMenuItemClick_exit = async (index: number) => {
  console.log(`你点击了选项 ${index}`);
  await logout();
};

// 处理搜索事件的函数
const handleSearch = () => {
  if (searchText.value.trim()) {
    // 这里可以触发搜索逻辑，例如发送请求等
    console.log("搜索内容：", searchText.value);
    // 你可以在这里添加更多的搜索逻辑，比如调用 API 接口
  }
};

// 计算属性，根据搜索关键词过滤书籍列表
const filteredBooklist = computed(() => {
  if (searchText.value.trim() === "") {
    return booklist.value;
  }
  const keyword = searchText.value.trim().toLowerCase();
  return booklist.value.filter((book) =>
    book.title.toLowerCase().includes(keyword)
  );
});
</script>


<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.el-header {
  /* background-color: gray; */
  background-color: #fff;
}

.el-aside {
  background-color: #fff;
  /* background-color: pink; */
  border: 1px solid #f5f6fe;
}

.el-main {
  background-color: #f5f6fe;
  /* background-color: orange; */
}

.el-menu {
  border-right: none;
}

.el-menu-vertical-demo:not(.el-menu--collapse) {
  width: 200px;
  min-height: 400px;
}

.input-with-select .el-input-group__prepend {
  background-color: var(--el-fill-color-blank);
}

.close-icon {
  position: absolute;
  top: 10px;
  right: 10px;
  cursor: pointer;
  font-size: 16px;
}

.el-row {
  margin-bottom: 20px;
}

.el-row:last-child {
  margin-bottom: 0;
}

.el-col {
  border-radius: 4px;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}

:global(h2#card-usage ~ .example .example-showcase) {
  background-color: var(--el-fill-color) !important;
}

p {
  margin: 0;
  padding: 0;
  font-size: 14px;
  text-align: left;
}

.p-vertically-center {
  display: flex;
  /* 使用 Flexbox 布局 */
  flex-direction: column;
  /* 垂直排列子元素 */
  justify-content: center;
  /* 垂直居中 */
  align-items: center;
  /* 水平居中 */
  height: 100%;
  /* 确保容器有高度 */
}

.p-vertically-center p {
  margin: 5px 40px;
  /* 为每个段落添加上下外边距 */
}

/* Vue 3 中使用 ::v-deep 穿透样式，将所有标签页标题文字加粗 */
::v-deep .el-tabs__item {
  font-weight: bold;
}

/* 确保弹出框有最小宽度 */
.el-popover {
  min-width: 120px;
  z-index: 1000;
  /* 确保弹出框显示在最上层 */
}

.booklistdiv {
  position: relative;
  margin: 20px;
  margin-bottom: 20px;
  background-color: #fff;
}

.booklistdiv::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(128, 128, 128, 0.5);
  z-index: 1;
  /* 确保覆盖层在图片之上 */
}

.booklistdiv p {
  margin: 0 0 5px 10px;
}

.book-image {
  width: 100%;
  height: 200px;
  object-fit: contain;
  display: block;
}

.booktitle {
  position: absolute;
  /* 设置为绝对定位 */
  bottom: 0;
  /* 让 booktitle 的底部与 booklistdiv 的底部重合 */
  left: 0;
  /* 左对齐 */
  width: 100%;
  /* 宽度占满父元素 */
  background-color: rgba(255, 255, 255, 1);
  /* 半透明背景 */
  color: black;
  /* 文字颜色 */
  padding: 5px;
  /* 内边距 */
  box-sizing: border-box;
  /* 包含内边距和边框在宽度内 */
  z-index: 2;
  /* 确保标题在覆盖层之上 */
  text-align: left;
  /* 让文字左对齐 */
}

.booktitle h4 {
  margin: 10px 0 10px 10px;
}

.icon {
  width: 1em;
  height: 1em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
}

.overflow-menu-icon {
  float: right;
  cursor: pointer;
  font-size: 20px;
}

.message-box-content {
  white-space: pre-line;
}

.badge-item {
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

.icon-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>